<script setup>
import { h, onMounted, reactive, ref, watch } from 'vue'
import {
    NIcon, NButton,
    NDataTable, NTooltip,
} from 'naive-ui'
import { PlusOutlined, EditOutlined, DeleteOutlined, ReloadOutlined } from '@vicons/antd'
import { useHttp } from '@/http';
import { timeFormat } from '@/utils/time';
import { checkPerms } from "@/utils/auth";
import Search from './components/search.vue'
import Add from './components/add.vue'
import Edit from './components/edit.vue'
const addRef = ref()
const editRef = ref()
const http = useHttp()
const columnsHandle = () => {
    const actionButton = (row) => {
        return [
            checkPerms(["sys:role:update"]) ? h(NButton, {
                strong: true,
                tertiary: true,
                type: "info",
                size: "small",
                onClick: () => editOpen(row.id)
            }, {
                icon: () => h(NIcon, null, { default: () => h(EditOutlined) }),
                default: () => "编辑"
            }) : null,
            checkPerms(["sys:role:del"]) ? h(NButton, {
                strong: true,
                tertiary: true,
                type: "error",
                size: "small",
                onClick: () => {
                    window.$dialog.info({
                        title: '提示',
                        content: `您确定要删除角色'${row.name}'吗?`,
                        positiveText: '确定',
                        negativeText: '取消',
                        onPositiveClick: () => {
                            const ids = [row.id];
                            delRole(ids);
                        },
                        onNegativeClick: () => { },
                    });
                }
            }, {
                icon: () => h(NIcon, null, { default: () => h(DeleteOutlined) }),
                default: () => "删除"
            }) : null]
    }
    const actionWidth = 90 * actionButton().filter(item => item != null).length
    const columns = [{
        type: "selection",
        key: "id",
        align: "center",
    },
    {
        title: "角色名称",
        key: "name",
        align: "center",
    },
    {
        title: "权限标识",
        key: "label"
    },
    {
        title: "备注",
        key: "remark",
        ellipsis: {
            tooltip: true
        }
    },
    {
        title: "创建时间",
        key: "createdTime",
        ellipsis: {
            tooltip: true
        },
        render(row) {
            return h("span", null, {
                default: () => timeFormat(row.createdTime)
            })
        }
    }, {
        title: "操作",
        key: "action",
        width: actionWidth,
        fixed: "right",
        render(row) {
            return h("div", { style: "width:100%;display:flex;justify-content:space-around;" },
                [...actionButton(row)])
        },
    }]
    return columns
}
const state = reactive({
    list: [],
    columns: columnsHandle(),
    delDisabled: true,
    checkedRowIds: [],
    rowKey: (row) => row.id,
    loading: false,
})
const searchState = reactive({
    form: {},
})
const paginationState = reactive({
    page: 1,
    pageSize: 10,
    itemCount: 0,
    showSizePicker: true,
    showQuickJumper: true,
    pageSizes: [10, 20, 40, 80],
})
// 打开新增
const openAdd = () => {
    addRef.value.open()
}
// 打开编辑
const editOpen = (id) => {
    editRef.value.open(id)
}
// 删除选中
const checkedDel = async () => {
    window.$dialog.info({
        title: "提示",
        content: `此操作将删除选中项您确定吗?`,
        positiveText: "确定",
        negativeText: "取消",
        onPositiveClick: () => {
            delRole(state.checkedRowIds);
        },
        onNegativeClick: () => { },
    });
};
// 删除角色
const delRole = async (ids) => {
    const res = await http.post("role/del", {
        ids: ids
    })
    window.$message.success(res.message)
    await refresh()
}
// 分页
const updatePage = async (e) => {
    paginationState.page = e
    await getList()
}
// 分页大小更新
const updatePageSize = async (e) => {
    paginationState.pageSize = e
    await getList()
}
const getList = async () => {
    state.loading = true
    const res = await http.get("role/list", {
        params: {
            pageNum: paginationState.page,
            pageSize: paginationState.pageSize,
            ...searchState.form,
        }
    })
    state.loading = false
    state.list = res.data.list
    paginationState.itemCount = res.data.count
}
const refresh = async () => {
    paginationState.page = 1
    paginationState.itemCount = 0
    await getList()
    state.checkedRowIds = [];
}
onMounted(async () => {
    await refresh()
})
// 按钮是否可操作
watch(
    () => state.checkedRowIds,
    (value) => {
        if (value.length == 0) {
            state.delDisabled = true;
        } else {
            state.delDisabled = false;
        }
    }
);
</script>
<template>
    <div class="page">
        <Search :refresh="refresh" v-model:value="searchState.form" />
        <div class="table-container">
            <div class="table-btn-container">
                <div>
                    <n-button class="btn-left" type="info" @click="openAdd" v-perms="['sys:role:add']">
                        <template #icon>
                            <n-icon>
                                <PlusOutlined />
                            </n-icon>
                        </template>
                        新增
                    </n-button>
                    <n-button class="btn-left" type="error" :disabled="state.delDisabled" @click="checkedDel"
                        v-perms="['sys:role:del']">
                        <template #icon>
                            <n-icon>
                                <DeleteOutlined />
                            </n-icon>
                        </template>
                        删除
                    </n-button>
                </div>
                <n-tooltip>
                    <template #trigger>
                        <n-icon class="refresh" size="22" @click="refresh">
                            <ReloadOutlined />
                        </n-icon>
                    </template>
                    <span>重载数据</span>
                </n-tooltip>
            </div>
            <n-data-table :columns="state.columns" :data="state.list" :row-key="state.rowKey" :loading="state.loading"
                :pagination="paginationState" remote @update:page="updatePage" @update:page-size="updatePageSize"
                v-model:checked-row-keys="state.checkedRowIds" />
        </div>
        <Add ref="addRef" :refresh="refresh" />
        <Edit ref="editRef" :refresh="refresh" />
    </div>
</template>
<style scoped>
.page {
    height: 100%;
}

.table-btn-container {
    margin-bottom: 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.table-container {
    background-color: #fff;
    padding: 16px;
}

.btn-left {
    margin-left: 10px;
}

.btn-left:first-child {
    margin-left: 0px;
}
</style>